//index.js
var req = require('../../interfaceImpl.js');
var config = require('../../interfaceConfig.js');
var zuodata = require("../../utils/zuodata.js");//座位的数据
var strAppCode = config.SmallApp;
var result;
var code = "";
var order = "";
var LockCheck_rows = '';
var LockCheck_graphcels = '';
var reqLockSeatSign = '';
var distanceList = [];
var xMove = "";
var yMove = "";
//获取应用实例
var Cinemapojo = '';
var plandate = '';
var danprice = '';
var totalprice = 0;
var showdate = '';
var ReqGetSeatMapSign = ''
const app = getApp()
// var row;
var col;
var Seat = '';
var showrow = [];
var showcol = [];
var noPaySeat = [];
var hasChooseSeat = [];
var oldDistence = '';
var newDistence = "";
var distance = "";
var distanceDiff = "";
var flag = 0;
var UserID = "";
var cancou = false;
var minSeatCol = "";

Page({
  data: {
    hangnumTop: 65,
    enlarge: 1,
    scrollTop: 0,
    scrollLeft: 0,
    toView:'',
    scale: 1.5,
    hangscale: 1,
    //座位数据
    zuolist: [],//座位数据
    chkzuolist: [],
    totalprice: totalprice,
    price: 0,//票价
    // payforprice: 0,//付钱价格
    tingnum: 0,//电影厅号
    dyid: 0,//电影id
    dyname: '',//电影名称
    yyid: 0, //影院id
    yyname: '', //影院名称
    tian: '',//今明后天
    chkday: '',//日期
    changciid: '',//场次id
    // time: '',//开场时间
    leixing: '',//电影类型

    isnoshow: true,//是否已经结束
    showbottom: false,//显示底线

    showmodel: false,//是否显示弹窗
    IsChoice: true,
    animationData: "",
    column: 0,
  },

  //页面的初始化
  onLoad: function (options) {

    wx.showLoading({
      title: '座位图生成中',
      mask: true
    })



    //TODO先判断是否登录
    UserID = app.globalData.cinemapojo.UserID
    hasChooseSeat = []
    Cinemapojo = JSON.parse(options.Cinemapojo);
    plandate = JSON.parse(options.plandate);
    danprice = plandate.pricesale1;//不确定
    showdate = options.showdate;
    var that = this;

    that.setData({
      Cinemapojo,
      plandate,
      showdate
    })
    //座位位置部分
    //TODO 请求座位图
    var getSeatMapSign = "strAppCode=" + strAppCode + "CinemaCode=" + Cinemapojo.CinemaCode + "PlanCodeApp=" + plandate.PlanCodeApp;
    return req.GetSignStr(getSeatMapSign).then(res => {
      if (res.data.success)
        ReqGetSeatMapSign = res.data.data
    }).then(() => {
      //   return req.GetSeatMap(strAppCode, Cinemapojo.CinemaCode, plandate.PlanCodeApp, ReqGetSeatMapSign).then(res => {
      //     showrow = [];
      //     showcol = [];

      //     row = res.data.data[0].maxSeatRow;
      //     col = res.data.data[0].maxSeatCol;
      //     minSeatCol = res.data.data[0].minSeatColres;


      //     that.setData({ showrow, showcol, heig: row, widt: col })
      //   })
      //   .then(() => {

      return req.GetPlanSiteState(strAppCode, Cinemapojo.CinemaCode, plandate.PlanCodeApp, ReqGetSeatMapSign).then(res => {
        var column = 0;
        var row = 0;
        var mincol = 0;
        Seat = res.data.data;
        mincol = Seat[0].ScreenCol;
        for (let i = 0; i < Seat.length; i++) {
          if (i == Seat.length - 1) {
            column = Seat[i].ScreenCol
            row = Seat[i].ScreenRow
          }
        }
        console.log(Seat)
        result = zuodata.getXiSeat(column, row, Seat);
        var num = 0;
        var finalres = [];
        for (var i = 0; i < result.length; i++) {
          for (var j = 0; j < result[i].col.length; j++) {
            if (result[i].col[j].SeatCode == '0000') {
              num++;
            }
          }
          if (num !== result[i].col.length) {
            //把这一列删除
            finalres.push(result[i])
          }
          num = 0;
        }

        for (var i = 0; i < finalres.length; i++) {
          finalres[i].row = i + 1;

        }
        // 节点
        console.log(result)
        result = finalres;
        var hangkuan = (column - mincol) + 1

        console.log('总的数据', hangkuan)
        that.setData({
          // zuolist: zuolist,
          result,
          column: hangkuan
        })
        setTimeout(function () {
          // 放在最后--
          wx.hideLoading();
        }
          , 1200)
      })
      //   })
    })
  },

  onShow: function () {
    this.setData({ hasclick: false })
    cancou = false;
  },


  bindscroll: function (e) {
    console.log('滚动了', e)
    // if (this.Isscroll) {
    //   console.log('存在值')
    //   clearTimeout(this.Isscroll);
    // }
    // this.Isscroll = setTimeout(() => {
    //   // this.setData({
    //   //   scrollLeft: e.detail.scrollLeft
    //   // })
    // }, 10);

  },
  hasBuy: function (e) {
    console.log('点击的事件', e)
    wx.showModal({
      title: '提示',
      showCancel: false,
      content: '该位置已经被购买，无法购买',
    })
    //计算出以谁为中心
    //x: currow * 30, y: curcol * 37.5,
    if (this.data.enlarge == 1) {
      var animation = wx.createAnimation({
        duration: 500,
        timingFunction: 'ease',
      })
      this.animation = animation

      animation.scale(2, 2).step().scale(1, 1).step();
      //导出动画
      this.setData({
        animationData: animation.export()
      })

      this.setData({
        scale: 1.5, hangscale: 1.5, enlarge: 2, hangnumTop: 0
      })
      setTimeout(() => {
        this.setData({
          scrollTop: e.target.offsetTop * 2+30,
          scrollLeft: e.target.offsetLeft * 2+30
        })
      },100)
    }
  },
  /**选座事件**/
  gochkzuo: function (e) {


    if (e.currentTarget.dataset.pojo.StateSeat != 0) {
      return false;
    }
    if (!this.data.IsChoice) {
      return;
    }
    this.data.IsChoice = false;
    setTimeout(() => {
      this.data.IsChoice = true;

    }, 500);
    // TODODODOD
    var currow = e.currentTarget.dataset.row
    var curcol = e.currentTarget.dataset.col
    //1.获取到 所选座位坐标
    //2.判断是否已经被选了如果是已经选了的 则修改状态为不选
    //选座部分

    for (var i = 0; i < result[currow - 1].col.length; i++) {
      console.log('这一行', result[currow - 1].col[i].SeatCol);
      console.log('当前的', curcol)
      if (result[currow - 1].col[i].SeatCol == curcol) {
        if (result[currow - 1].col[i].haschoose == true) {
          console.log('介个座位已经有人选了')
          result[currow - 1].col[i].haschoose = false;
          for (var j = 0; j < hasChooseSeat.length; j++) {
            if (hasChooseSeat[j].SeatRow == currow && hasChooseSeat[j].SeatCol == curcol) {
              hasChooseSeat.splice(j, 1)

            }
          }
        } else {
          if (hasChooseSeat.length >= 4) {
            wx.showModal({
              title: '提示',
              content: '一次最多可选择四个座位',
              showCancel: false
            })
            return false;
          }

          result[currow - 1].col[i].haschoose = true; hasChooseSeat.push(result[currow - 1].col[i])
          //计算出以谁为中心
          console.log(currow)
          //x: currow * 30, y: curcol * 37.5,
          if (this.data.enlarge == 1) {
            var animation = wx.createAnimation({
              duration: 500,
              timingFunction: 'ease',
            })
            this.animation = animation

            animation.scale(2, 2).step().scale(1, 1).step();
            //导出动画
            this.setData({
              animationData: animation.export()
            })
            setTimeout(() => {
              this.setData({
                scrollTop: e.target.offsetTop * 2 + 30,
                scrollLeft: e.target.offsetLeft * 2
              }) + 30
            }, 100)
          }
          console.log(result[currow - 1].col[i].SeatCode);

          this.setData({
            scale: 1.5, hangscale: 1.5, enlarge: 2, hangnumTop: 0, toView: result[currow - 1].col[i].SeatCode
          })
         
          console.log(curcol)
        }
        totalprice = danprice * hasChooseSeat.length
        this.setData({ result, hasChooseSeat, totalprice })
        break;
      }
    }
  },


  // htouchmove: function (e) { //初次手指触摸后移动为横向的移动
  //   console.log(e)
  // },

  // vtouchmove: function (e) { //初次手指触摸后移动为纵向的移动
  //   console.log(e)
  // },
  scrollTouchstart: function (e) {

    if (e.touches.length == 2) {//二指缩放
      if (!this.data.IsChoice) {
        return;
      }
      this.data.IsChoice = false;
      setTimeout(() => {
        this.data.IsChoice = true;
      }, 500);


      xMove = e.touches[1].clientX - e.touches[0].clientX
      yMove = e.touches[1].clientY - e.touches[0].clientY
      distance = Math.sqrt(xMove * xMove + yMove * yMove);//开根号

      if (flag == 0 || flag % 2 != 0) { //先滑动
        oldDistence = distance
      } else if (flag !== 0 && flag % 2 == 0) {
        newDistence = distance
      }
      flag = flag + 2;
      if (oldDistence !== '' && newDistence !== "") {
        distanceDiff = newDistence - oldDistence
      }


      if (distanceDiff > 0) {
        this.setData({ enlarge: 1 })
      } else {
        if (this.data.enlarge == 1) {
          var animation = wx.createAnimation({
            duration: 500,
            timingFunction: 'ease',
          })
          this.animation = animation

          animation.scale(2, 2).step().scale(1, 1).step();

          //导出动画
          this.setData({
            animationData: animation.export()
          })
        }

        this.setData({ enlarge: 2, hangnumTop: 0 })
      }

    }
  },
  bindTouchMove: function (e) {
    // console.log(e)
    if (e.touches.length == 2) {//二指缩放
      xMove = e.touches[1].clientX - e.touches[0].clientX
      yMove = e.touches[1].clientY - e.touches[0].clientY
      distance = Math.sqrt(xMove * xMove + yMove * yMove);//开根号

      if (flag == 0 || flag % 2 != 0) { //先滑动
        oldDistence = distance
      } else if (flag !== 0 && flag % 2 == 0) {
        newDistence = distance
      }
      flag = flag + 2;
      if (oldDistence !== '' && newDistence !== "") {
        distanceDiff = newDistence - oldDistence
      }


      if (distanceDiff > 0) {
        this.setData({ scale: 1.5, hangscale: 1.5 })
      } else {

        this.setData({ scale: 0.8, hangscale: 0.8 })
      }

    }

  },

  bindchange: function (e) {
    // console.log(e)
    this.setData({ hangscale: this.data.scale })
  },
  bindscale: function (e) {
    console.log(e)
    this.setData({ hangscale: e.detail.scale })
  },



  //确定去支付
  gopayfor: function (e) {
    LockCheck_rows = '';
    LockCheck_graphcels = '';
    var that = this;
    //判断是否选择座位
    var chknum = hasChooseSeat.length;
    if (chknum == 0) {
      wx.showModal({
        title: '提示',
        content: '您没有选择座位！请选择',
        showCancel: false
      })
      return false;
    } else {
      //TOTO锁座
      var PriceTotal = 0;
      var SeatInfo = "";
      for (var i = 0; i < hasChooseSeat.length; i++) {
        PriceTotal += plandate.pricesale1;
        if (hasChooseSeat.length > 1 && i < (hasChooseSeat.length - 1)) {
          SeatInfo += hasChooseSeat[i].SeatCode + "," + plandate.pricesale1 + "," + "0," + hasChooseSeat[i].Seattext + "|";
          LockCheck_rows = LockCheck_rows + hasChooseSeat[i].Seattext + ",";
          console.log(LockCheck_rows)
          console.log(hasChooseSeat[i].ScreenCol)
          LockCheck_graphcels = LockCheck_graphcels + hasChooseSeat[i].ScreenCol + ","
        } else {
          SeatInfo += hasChooseSeat[i].SeatCode + "," + plandate.pricesale1 + "," + "0," + hasChooseSeat[i].Seattext;
          LockCheck_rows = LockCheck_rows + hasChooseSeat[i].Seattext;
          console.log(LockCheck_rows)
          console.log(hasChooseSeat[i].ScreenCol)
          LockCheck_graphcels = LockCheck_graphcels + hasChooseSeat[i].ScreenCol
        }

      }

      return req.LockCheck(LockCheck_rows, LockCheck_graphcels).then(res => {
        if (res.data.success) {

          var LockSeatSign = "strAppCode=" + strAppCode + "AddTypeID=" + app.globalData.cinemapojo.AddTypeID + "FeatureAppNo=" + plandate.PlanCodeApp + "PriceTotal=" + PriceTotal + "SeatInfo=" + SeatInfo + "UserID=" + UserID + "PayPhone=" + app.globalData.loginuserinfo.mobile;
          return req.GetSignStr(LockSeatSign).then(res => {
            if (res.data.success)
              reqLockSeatSign = res.data.data;
            that.setData({ hasclick: true })
          }).then(() => {
            return req.LockSeat(strAppCode, plandate.AddTypeID, plandate.PlanCodeApp, PriceTotal, SeatInfo, UserID, app.globalData.loginuserinfo.mobile, reqLockSeatSign, app.globalData.token).then(res => {
              if (res.data.success) {
                order = res.data.data;
                console.log(order)
                cancou = true;
              } else {
                wx.showToast({
                  title: '锁座失败,请选择别的座位',
                  icon: none,
                  success: function () {
                    that.setData({ hasclick: false })
                    return
                  }
                })
                return;
              }

            }).then(() => {
              if (cancou) {
                // 显示遮罩层
                var animation = wx.createAnimation({
                  duration: 200,
                  timingFunction: "linear",
                  delay: 0
                })

                that.animation = animation
                animation.translateY(300).step();

                that.setData({
                  animationData: animation.export(),
                  showmodel: true,//显示弹出层
                })
                setTimeout(function () {
                  animation.translateY(0).step()
                  that.setData({
                    animationData: animation.export()
                  })
                }.bind(that));
              }

            })
          })


        } else {
          //测试用

          wx.showModal({
            title: '提示',
            showCancel: false,
            content: res.data.msg,
          })
        }
      })


    }
  },
  /**点击关闭按钮***/
  hidemodal: function () {
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showmodel: false,//隐藏弹出层
      })

    }.bind(this), 200)
  },
  //我知道了，跳转到支付页面
  goconfirm: function () {
    var that = this;
    that.hidemodal();
    wx.redirectTo({
      url: '../payfor/index?TotalMoney=' + totalprice + '&&order=' + JSON.stringify(order) + '&&hasChooseSeat=' + JSON.stringify(hasChooseSeat) + '&&plandate=' + JSON.stringify(plandate) + '&&showdate=' + showdate + "&&cinema=" + JSON.stringify(Cinemapojo),
    })
  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

    var that = this;
    that.setData({
      showbottom: true
    })
  },
})
